package cn.openea.perpartner.meily.web.controller;

import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.web.controller.BaseController;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.common.core.web.page.TableDataInfo;
import cn.openea.perpartner.meily.web.entity.Goods;
import cn.openea.perpartner.meily.web.entity.GroupBuyingSub;
import cn.openea.perpartner.meily.web.entity.dto.GroupBuyingSubDTOFactory;
import cn.openea.perpartner.meily.web.entity.dto.GroupBuyingSubDTOFactory.SalesCommissionDTO;
import cn.openea.perpartner.meily.web.entity.dto.GroupDto;
import cn.openea.perpartner.meily.web.entity.vo.GroupBuyingSubEditVo;
import cn.openea.perpartner.meily.web.entity.vo.OrderRefundVo;
import cn.openea.perpartner.meily.web.service.IGoodsService;
import cn.openea.perpartner.meily.web.service.IGroupBuyingSubService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.ParseException;
import java.util.List;
import java.util.Optional;

/**
 * (GroupBuyingSub)表控制层
 *
 * @author rains
 * @since 2023-02-08 17:35
 */
@Api(tags = "团购")
@RestController
@RequestMapping("/buying")
public class GroupBuyingSubController extends BaseController {

    @Resource
    private IGroupBuyingSubService groupBuyingSubService;
    @Resource
    private GroupBuyingSubDTOFactory groupBuyingSubDTOFactory;

    @Autowired
    private IGoodsService goodsService;

    @ApiOperation("是否可参与团购")
    @PostMapping("/canJoin")
    public AjaxResult canJoin(@RequestBody GroupDto groupDto){
        return this.groupBuyingSubService.canJoin(groupDto);
    }

    @ApiOperation("参与团购")
    @PostMapping("/join")
    public AjaxResult join(@RequestBody GroupBuyingSub groupBuyingSub) throws ParseException {
        return this.groupBuyingSubService.join(groupBuyingSub);
    }

    @ApiOperation("确认收货")
    @PostMapping("/confirmReceipt")
    public AjaxResult confirmReceipt(@RequestBody GroupBuyingSub groupBuyingSub) {
        return this.groupBuyingSubService.confirmReceipt(groupBuyingSub);
    }

    @ApiOperation("直接购买商品")
    @PostMapping("/directPurchase")
    public AjaxResult directPurchase(@RequestBody GroupBuyingSub groupBuyingSub) throws ParseException {
        return this.groupBuyingSubService.directPurchase(groupBuyingSub);
    }

    @ApiOperation("确认收货-直接购买")
    @PostMapping("/confirmReceipt2")
    public AjaxResult confirmReceipt2(@RequestBody GroupBuyingSub groupBuyingSub) {
        return this.groupBuyingSubService.confirmReceipt2(groupBuyingSub);
    }

    @ApiOperation("获取参与团购记录详情")
    @PostMapping("/getOrderDetails")
    public AjaxResult getOrderDetails(@RequestBody GroupDto groupDto) throws ParseException {
        return this.groupBuyingSubService.getOrderDetails(groupDto);
    }

    @ApiOperation("获取参与团购记录列表---分页")
    @PostMapping("/getJoinRecordList")
    public TableDataInfo getJoinRecordList(@RequestBody GroupDto groupDto) throws ParseException {
        startPage();
        List<GroupBuyingSub> list = this.groupBuyingSubService.getJoinRecordList(groupDto);
        return getDataTable(list);
    }

    @ApiOperation("根据分享验证id给消费者发放分享报酬")
    @PostMapping("/sendShareRewardByVerificationId")
    public AjaxResult sendShareRewardByVerificationId(@RequestBody JSONObject object) {
        if (object.isEmpty()) {
            return AjaxResult.error("获取不到参数！");
        }
        return this.groupBuyingSubService.sendShareRewardByVerificationId(object.getString("shareValidationId"));
    }

    @ApiOperation("保存分享海报地址")
    @PostMapping("/saveSharePictureUrl")
    public AjaxResult saveSharePictureUrl(@RequestBody JSONObject object) {
        if (object.isEmpty()) {
            return AjaxResult.error("获取不到参数！");
        }
        return this.groupBuyingSubService.saveSharePictureUrl(object);
    }

    @ApiOperation("获取分享海报地址")
    @PostMapping("/getharePictureUrl")
    public AjaxResult getharePictureUrl(@RequestBody JSONObject object) {
        if (object.isEmpty()) {
            return AjaxResult.error("获取不到参数！");
        }
        return this.groupBuyingSubService.getharePictureUrl(object);
    }

    @ApiOperation("首次打开分享发通知")
    @PostMapping("/firstOpenShareSendMsg")
    public AjaxResult firstOpenShareSendMsg(@RequestBody JSONObject object) throws Exception {
        if (object.isEmpty()) {
            return AjaxResult.error("获取不到参数！");
        }
        return this.groupBuyingSubService.firstOpenShareSendMsg(object);
    }

    @ApiOperation("保存评价")
    @PostMapping("/evaluation")
    public AjaxResult saveEvaluation(@RequestBody GroupBuyingSub groupBuyingSub) throws Exception {
        if (!this.groupBuyingSubService.saveEvaluation(groupBuyingSub)) {
            return AjaxResult.error("保存失败！");
        }
        return AjaxResult.success("保存成功！");
    }

    @ApiOperation("根据订单id获取参与团购记录详情")
    @GetMapping("/info/byOrderId/{orderId}")
    public AjaxResult infoByOrderId(@PathVariable String orderId) {
        if (StrUtil.isBlank(orderId)) {
            return AjaxResult.error("获取不到orderId！");
        }
        LambdaQueryWrapper<GroupBuyingSub> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GroupBuyingSub::getOrderId, orderId);
        return AjaxResult.success("获取参与团购记录详情成功！", groupBuyingSubService.getOne(wrapper));
    }

    @ApiOperation("获取用户当前周期已购买商品的数量")
    @PostMapping("/getQuantityByCurrentCycle")
    public AjaxResult getQuantityByCurrentCycle(@RequestBody GroupBuyingSub groupBuyingSub) {
        if (StrUtil.isBlank(groupBuyingSub.getPartnerId())) {
            return AjaxResult.error("获取不到当前用户的userid，请检查是否登录！");
        }
        return AjaxResult.success("获取用户当前周期已购买商品的数量成功！", groupBuyingSubService.getQuantityByCurrentCycle(groupBuyingSub));
    }

    @ApiOperation("团购退款")
    @PostMapping("/order/refund")
    public AjaxResult refund(@RequestBody @Valid OrderRefundVo orderRefundVo) {
        boolean refundResult = groupBuyingSubService.refund(orderRefundVo);
        return refundResult ? AjaxResult.success() : AjaxResult.error("微信退款成功，钱包退款失败，请联系系统管理人员处理");
    }

    @ApiOperation("团购佣金详情")
    @GetMapping("/purchase/commission/details/{id}")
    public AjaxResult purchaseCommissionDetails(@PathVariable String id) {
        GroupBuyingSub groupBuyingSub = Optional.ofNullable(groupBuyingSubService.getById(id))
                .orElseThrow(() -> new ServiceException("团购订单不存在"));
        SalesCommissionDTO salesCommissionDTO = groupBuyingSubService.findPurchaseCommissionDetailsById(groupBuyingSub);
        return AjaxResult.success(salesCommissionDTO);
    }

    @ApiOperation("修改收货信息")
    @PostMapping("/modifyReceivingInfo")
    public AjaxResult modifyReceivingInfo(@RequestBody GroupBuyingSub groupBuyingSub) {
        return this.groupBuyingSubService.modifyReceivingInfo(groupBuyingSub);
    }

    /**
     * ******************** 以下是后台管理用到的 *******************************
     */

    @ApiOperation("meily-购买记录详情")
    @GetMapping("/get/{id}")
    public AjaxResult getById(@PathVariable("id") Long id) {
        GroupBuyingSub groupBuyingSub = groupBuyingSubService.getById(id);

        // 购买数量
        String buyQuantity = groupBuyingSub.getBuyQuantity();

        // 线上服务商分销报酬
        Goods goods = goodsService.getById(groupBuyingSub.getGoodsId());
        String foremanReward = goods.getForemanReward();

        // 计算服务商佣金（元）
        double totalReward = Double.parseDouble(foremanReward) * Long.parseLong(buyQuantity);

        // 此字段暂时无用，用来保存 服务商佣金（元）
        groupBuyingSub.setSceneId(String.format("%.2f", totalReward));

        return success(groupBuyingSubDTOFactory.toDetailsDto.apply(groupBuyingSub));
    }

    @ApiOperation("meily-团购订单数据更改")
    @PostMapping("/update/groupBuy/order")
    public AjaxResult updateGroupBuyOrder(@RequestBody @Valid GroupBuyingSubEditVo editVo) {
        groupBuyingSubService.updateGroupBuyOrder(editVo);
        return AjaxResult.success();
    }
}
